package com.lanou.connotationjoke.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.connotationjoke.view.NewListView;
import com.lanou.connotationjoke.R;
import com.lanou.connotationjoke.view.RefreshableView;
import com.lanou.connotationjoke.adapter.HomePictureListViewAdapter;
import com.lanou.connotationjoke.db.HomePictureEntity;
import com.lanou.connotationjoke.db.HomePictureEntityDao;
import com.lanou.connotationjoke.entity.AppUrl;
import com.lanou.connotationjoke.entity.CommentEty;
import com.lanou.connotationjoke.entity.CurrentItemEty;
import com.lanou.connotationjoke.entity.DataDetialEty;
import com.lanou.connotationjoke.entity.GroupEty;
import com.lanou.connotationjoke.entity.JsonEty;
import com.lanou.connotationjoke.entity.LargeImageEty;
import com.lanou.connotationjoke.entity.UserEty;
import com.lanou.connotationjoke.tool.DaoSingleton;
import com.lanou.connotationjoke.tool.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by dllo on 16/1/8.
 */
public class HomePictureFragment extends BaseFragment{
    private RefreshableView refreshableView;
    private NewListView listView;
    private HomePictureListViewAdapter adapter;
    private final String URL = AppUrl.HOMEPICTURE;
    private List<DataDetialEty> datas;
    private HomePictureEntityDao homePictureEntityDao
            = DaoSingleton.getInstance().getHomePictureEntityDao();
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            EventBus.getDefault().post("stop");
            return false;
        }
    });
    private static boolean isRegister;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_picture,null);
        refreshableView = (RefreshableView) view.findViewById(R.id.refresh_picture);
        listView = (NewListView) view.findViewById(R.id.listview_home_picture);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (isRegister == false){
            EventBus.getDefault().register(this);
            isRegister = true;
        }

            VolleySingleton.addRequest(URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    JsonEty jsonEty = gson.fromJson(response, JsonEty.class);
                    if (null != jsonEty&&null != jsonEty.getData()) {
                        datas = jsonEty.getData().getData();
                        adapter = new HomePictureListViewAdapter(getActivity(), datas);
                        listView.setAdapter(adapter);
                        insertOrReplaceToHomePictureEntityDao(datas);
                        handler.sendEmptyMessage(0);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    datas = getDataFromHomePictureEntityDao();
                    adapter = new HomePictureListViewAdapter(getActivity(),datas);
                    listView.setAdapter(adapter);
                    handler.sendEmptyMessage(0);
                }
            });

        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                    VolleySingleton.addRequest(URL, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Gson gson = new Gson();
                            JsonEty jsonEty = gson.fromJson(response, JsonEty.class);
                            datas = jsonEty.getData().getData();
                            adapter.refreshData(datas);
                            insertOrReplaceToHomePictureEntityDao(datas);
                            refreshableView.finishRefreshing();
                            handler.sendEmptyMessage(0);
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            refreshableView.finishRefreshing();
                            handler.sendEmptyMessage(0);
                        }
                    });
            }
        }, 2);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        isRegister = false;
    }




    /**
     *
     * @param currentItemEty
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onMainEvent(CurrentItemEty currentItemEty) {
        if (currentItemEty.getI() == 2){
            listView.setSelection(0);
            new Thread() {
                @Override
                public void run() {
                    final long downTime = SystemClock.currentThreadTimeMillis();

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent down = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_DOWN, 10, 300, 0);
                            listView.dispatchTouchEvent(down);
                        }
                    });


                    SystemClock.sleep(50);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent move = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_MOVE, 10, 700, 0);
                            listView.dispatchTouchEvent(move);
                        }
                    });


                    SystemClock.sleep(50);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent move = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_MOVE, 10, 1000, 0);
                            listView.dispatchTouchEvent(move);
                        }
                    });

                    SystemClock.sleep(1000);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MotionEvent up = MotionEvent.obtain(downTime, SystemClock.currentThreadTimeMillis(), MotionEvent.ACTION_UP, 10, 1000, 0);
                            listView.dispatchTouchEvent(up);
                        }
                    });
                }
            }.start();


        }

    }








    private void insertOrReplaceToHomePictureEntityDao(List<DataDetialEty> datas){
        homePictureEntityDao.deleteAll();
        for (DataDetialEty dataDetialEty:datas){
            if (dataDetialEty.getGroup()!=null&&dataDetialEty.getGroup().getLarge_image()!=null) {
                String avatar_url = dataDetialEty.getGroup().getUser().getAvatar_url();
                String name = dataDetialEty.getGroup().getUser().getName();
                String content = dataDetialEty.getGroup().getContent();
                String category_name = dataDetialEty.getGroup().getCategory_name();
                String uri = dataDetialEty
                        .getGroup()
                        .getLarge_image()
                        .getUri();
                int digg_count = dataDetialEty.getGroup().getDigg_count();
                int bury_count = dataDetialEty.getGroup().getBury_count();
                int comment_count = dataDetialEty.getGroup().getComment_count();
                int share_count = dataDetialEty.getGroup().getShare_count();
                String share_url = dataDetialEty.getGroup().getShare_url();
                String avatar_url_comment = null;
                String user_name_comment = null;
                int digg_count_comment = 0;
                String text_comment = null;
                if (dataDetialEty.getComments().size()>0){
                    avatar_url_comment = dataDetialEty.getComments().get(0).getAvatar_url();
                    user_name_comment = dataDetialEty.getComments().get(0).getUser_name();
                    digg_count_comment = dataDetialEty.getComments().get(0).getDigg_count();
                    text_comment = dataDetialEty.getComments().get(0).getText();
                }

                homePictureEntityDao.insert(new HomePictureEntity(homePictureEntityDao.count(), avatar_url, name, content, category_name, uri, avatar_url_comment,
                        user_name_comment, digg_count_comment, text_comment, digg_count, bury_count, comment_count, share_count,share_url));
            }
        }
    }


    private List<DataDetialEty> getDataFromHomePictureEntityDao(){
        List<DataDetialEty> datas = new ArrayList<>();
        List<HomePictureEntity> homePictureEntities = homePictureEntityDao.queryBuilder().list();
        for (HomePictureEntity homePictureEntity:homePictureEntities){
            DataDetialEty dataDetialEty = new DataDetialEty();
            GroupEty groupEty = new GroupEty();
            List<CommentEty> commentEties = new ArrayList<>();
            CommentEty commentEty = new CommentEty();
            UserEty userEty = new UserEty();
            LargeImageEty largeImageEty = new LargeImageEty();
            userEty.setAvatar_url(homePictureEntity.getAvatar_url());
            userEty.setName(homePictureEntity.getName());
            groupEty.setUser(userEty);
            groupEty.setContent(homePictureEntity.getContent());
            groupEty.setCategory_name(homePictureEntity.getCategory_name());
            largeImageEty.setUri(homePictureEntity.getUri());
            groupEty.setLarge_image(largeImageEty);
            groupEty.setDigg_count(homePictureEntity.getDigg_count());
            groupEty.setBury_count(homePictureEntity.getBury_count());
            groupEty.setComment_count(homePictureEntity.getComment_count());
            groupEty.setShare_count(homePictureEntity.getShare_count());
            groupEty.setShare_url(homePictureEntity.getShare_url());
            if (homePictureEntity.getAvatar_url_comment()!=null) {
                commentEty.setAvatar_url(homePictureEntity.getAvatar_url_comment());
                commentEty.setUser_name(homePictureEntity.getUser_name_comment());
                commentEty.setDigg_count(homePictureEntity.getDigg_count_comment());
                commentEty.setText(homePictureEntity.getText_comment());
                commentEties.add(commentEty);
            }
            dataDetialEty.setGroup(groupEty);
            dataDetialEty.setComments(commentEties);
            datas.add(dataDetialEty);
        }
        return datas;
    }


}
